﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;
using System.Net;
using Exceptionless;
using Brc_PaaS.Common.Model.Basic;
using Exceptionless.Logging;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Threading.Tasks;
using Brc_PaaS.Core.Exceptionless;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc;

namespace Brc_PaaS.Api.Filters
{
    /// <summary>
    /// 异常拦截中间件
    /// </summary>
    public class GlobalExceptionFilter : Attribute, IExceptionFilter
    {
        //private readonly RequestDelegate next;
        /// <summary>
        /// 构造函数
        /// </summary>
        public GlobalExceptionFilter()
        {
            
        }
        /// <summary>
        /// 处理异常
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            if (!context.ExceptionHandled)
            {
                var cad = context.ActionDescriptor as ControllerActionDescriptor;
                var isAdmin = cad.ControllerName.StartsWith("PaaS");
                Task.Run(() => {
                    ExceptionlessClient.Default.CreateException(context.Exception).SetUserIdentity("0000", "PaaS").AddTags(new string[] { "PaaSException", isAdmin ? "AdminException" : "CustomException" }).Submit();
                });
                var result = new BaseResponseModel() { IsSuccess = false, Msg = "对不起，处理您的请求时出错，请联系管理员" };
                context.Result = new JsonResult(result);
            }
            context.ExceptionHandled = true;
        }
        /// <summary>
        /// 异步发生异常时进入
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task OnExceptionAsync(ExceptionContext context)
        {
            OnException(context);
            return Task.CompletedTask;
        }      
    }
}